package com.gin.no_gay_alliance.customview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.utils.InputMethodManagerUtils;
import com.gin.no_gay_alliance.utils.MyHandler;

import java.lang.ref.WeakReference;
import java.util.Locale;

/**
 * 翻页器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/15 16:51
 **/
public class PagerButton extends androidx.appcompat.widget.AppCompatButton implements View.OnClickListener {
    public static final String TAG = PagerButton.class.getSimpleName();
    int page;
    int totalPage;
    /**
     * 是否强制限制输入范围
     */
    boolean limit = true;
    OnPageChangedListener onPageChangedListener;
    WeakReference<Activity> activityWeakReference;

    MyHandler handler;

    public PagerButton(@NonNull Context context) {
        super(context);
        setOnClickListener(this);
    }

    public PagerButton(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(this);
    }

    public PagerButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnClickListener(this);
    }

    public void init(Activity activity, MyHandler handler,
                     OnPageChangedListener onPageChangedListener) {
        setActivityWeakReference(activity);
        setHandler(handler);
        setOnPageChangedListener(onPageChangedListener);
    }

    /**
     * 修改页数文本
     *
     * @param page      当前页
     * @param totalPage 最大页
     */
    public void setData(int page, int totalPage) {
        this.page = page;
        this.totalPage = totalPage;
        setText(String.format(Locale.CHINA, "%d / %d", page, totalPage));
    }

    @Override
    @SuppressLint("InflateParams")
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pager, null);
        TextView tv = view.findViewById(R.id.page_text);
        EditText editText = view.findViewById(R.id.et);
        tv.setText(String.format(Locale.CHINA, "请输入页码: 1 ~ %d", totalPage));
        editText.setText(String.valueOf(page));
        editText.addTextChangedListener(new TextWatcher() {
            /**
             * 修改之前的值
             */
            int value;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                value = ObjectUtils.isEmpty(s) ? 1 : Integer.parseInt(s.toString());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (ObjectUtils.isEmpty(s)) {
                    return;
                }
                int newValue = Integer.parseInt(s.toString());
                if (newValue > totalPage && limit) {
                    editText.setText(String.valueOf(totalPage));
                    editText.setSelection(editText.getText().length(), editText.getText().length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        builder.setView(view);
        builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
            int page = Integer.parseInt(editText.getText().toString());
            if (onPageChangedListener != null) {
                onPageChangedListener.onPageChanged(page);
            }
        });
        builder.setNeutralButton("首页", (dialog, which) -> {
            if (onPageChangedListener != null) {
                onPageChangedListener.onPageChanged(1);
            }
        });
        builder.setNegativeButton("尾页", (dialog, which) -> {
            if (onPageChangedListener != null) {
                onPageChangedListener.onPageChanged(totalPage);
            }
        });

        builder.setOnCancelListener(dialog -> hideInput(editText));
        builder.setOnDismissListener(dialog -> hideInput(editText));
        builder.create().show();
        editText.requestFocus();
        editText.setSelection(0, editText.getText().length());


        if (activityWeakReference != null) {
            Activity activity = activityWeakReference.get();
            if (activity != null && handler != null) {
                System.out.println("激活输入法");
                handler.postDelayed(() -> InputMethodManagerUtils.show(editText), 300);
            }
        }
    }

    private void hideInput(View view) {
        if (activityWeakReference != null) {
            Activity activity = activityWeakReference.get();
            if (activity != null) {
                InputMethodManagerUtils.hide(view);
            }
        }
    }

    public void setActivityWeakReference(Activity activity) {
        this.activityWeakReference = new WeakReference<>(activity);
    }

    public void setHandler(MyHandler handler) {
        this.handler = handler;
    }

    public void setLimit(boolean limit) {
        this.limit = limit;
    }

    public void setOnPageChangedListener(OnPageChangedListener onPageChangedListener) {
        this.onPageChangedListener = onPageChangedListener;
    }

    public interface OnPageChangedListener {
        /**
         * 翻页器执行翻页操作时的回调
         *
         * @param page 目标页数
         */
        void onPageChanged(int page);
    }
}
